'use strict';

define(['controllers', '../service/loginService', '../../common/service/menuService'], function (controllers) {
    controllers.home.register('LoginController', ['$scope', '$rootScope', '$location', 'LoginService', 'MenuService', function ($scope, $rootScope, $location, loginService, menuService) {
        $scope.init = function () {
            $scope.pageNo = 1;
            $scope.pageSize = 10;

            $scope.account = getAccountFromCookie();
            $scope.password = '';

            $scope.err = false;
            $scope.errMsg = '';
        };

        $scope.initEvent = function () {
            $(document).ready(function () {
                $('#account').select();
            });

            $('#account, #password').keypress(function (e) {
                if (isSubmitKeyCode(e)) {
                    $scope.login();
                    return false;
                }
            });
        };

        $scope.login = function () {
            $scope.err = false;
            loginService.login($scope.account, $scope.password, function() {
                setAccountToCookie($scope.account);
                menuService.reloadMenus($rootScope);
                $location.path(menuService.getDefaultMenuUrl());
            }, function (errMsg) {
                $scope.err = true;
                $scope.errMsg = errMsg;
                $('#account').select();
                return false;
            });
        };

        $scope.init();
        $scope.initEvent();
    }]);
});